/**
 * @file port_ble_base.c
 * @brief 
 * @author dotc (dotchan@qq.com)
 * @date 2025-01-21
 * 
 * @copyright Copyright (c) 2025 by 深圳市鹏天微智能科技有限公司, All Rights Reserved.
 */

#if defined(CONFIG_PORT_BLE_ENABLE)

/* ==================== [Includes] ========================================== */

#include "xf_ble_gap.h"
#include "xf_ble_gatt_common.h"
#include "xf_utils.h"
#include "xf_init.h"
#include "port_ble_base.h"


#include "drvs.h"

/* ==================== [Defines] =========================================== */

#define TAG "port_ble_base"

/* ==================== [Typedefs] ========================================== */

/* ==================== [Static Prototypes] ================================= */

/* ==================== [Static Variables] ================================== */

static port_ble_app_t s_list_app[DEFAULT_BLE_APP_MAX_CNT] = {0};

// __VAR_ENV 
static port_ble_gatt_info_t s_global_gatt_info = {
    .start_hdl = 1,
};

/* ==================== [Macros] ============================================ */

/* ==================== [Global Functions] ================================== */

uint8_t port_gatt_app_id_alloc(void)
{
    uint8_t index = 0;
    for(; index < DEFAULT_BLE_APP_MAX_CNT; index++)
    {
        if(s_list_app[index].app_id == XF_BLE_GATT_APP_ID_INVALID)
        {
            s_list_app[index].app_id = PORT_GATT_APP_LIST_INDEX_TO_ID(index);
            s_list_app[index]._p_all = NULL;
            return s_list_app[index].app_id;
        }
    }
    return XF_BLE_GATT_APP_ID_INVALID;
}

port_ble_app_t *port_gatt_app_list_get(void)
{
    return s_list_app;
}

port_ble_app_t *port_gatt_app_get(uint8_t app_id)
{
    uint8_t index = 0;
    for(; index < DEFAULT_BLE_APP_MAX_CNT; index++)
    {
        if(s_list_app[index].app_id == app_id)
        {
            return &s_list_app[index];
        }
    }
    return NULL;
}

port_ble_app_t *port_gatt_app_get_by_conn_id(uint8_t conn_id)
{
    uint8_t index = 0;
    for(; index < DEFAULT_BLE_APP_MAX_CNT; index++)
    {
        if(s_list_app[index].conn_id == conn_id)
        {
            return &s_list_app[index];
        }
    }
    return NULL;
}

uint16_t port_gatt_handle_alloc(void)
{
    uint16_t hdl = s_global_gatt_info.start_hdl++;
    XF_LOGD(TAG, "GET ATT HDL:%d", hdl);
    return hdl;
}

uint16_t port_gatt_start_handle_get(void)
{
    return s_global_gatt_info.start_hdl;
}

void port_gatt_start_handle_set(uint16_t handle)
{
    s_global_gatt_info.start_hdl = handle;
}

/* ==================== [Static Functions] ================================== */

#endif
